package com.ld.shieldsb.canalclient.handler.impl;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import com.ld.shieldsb.canalclient.handler.ICanalDataSyncHandler;
import com.ld.shieldsb.common.core.ServiceFactory;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CanalDataHandlerFactory extends ServiceFactory<ICanalDataSyncHandler> {

    static {
        // 注意工厂类不要一开始就注册对象，否则可能缺少必要的jar包不能实例化报错，应该注册类
        getInstance().registerServiceClass(Data2LoggerHandler.TYPE_NAME, Data2LoggerHandler.class); // 日志打印
        getInstance().registerServiceClass(Data2RollingFileHandler.TYPE_NAME, Data2RollingFileHandler.class); // 同步到文件处理器
        getInstance().registerServiceClass(Data2RDbHandler.TYPE_NAME, Data2RDbHandler.class); // 同步到数据库处理器
        getInstance().registerServiceClass(Data2SolrHandler.TYPE_NAME, Data2SolrHandler.class); // 同步到solr处理器
    }

    public static ServiceFactory<ICanalDataSyncHandler> getInstance() {
        return getInstance(CanalDataHandlerFactory.class);
    }

    /**
     * 获取属性描述map
     * 
     * @Title getPropertiesDespMap
     * @author 吕凯
     * @date 2021年12月11日 下午2:42:00
     * @return Map<String,String>
     */
    public static Map<String, String> getPropertiesDespMap() {
        Set<String> keys = CanalDataHandlerFactory.getInstance().getAllKey();
        Map<String, String> resultMap = new LinkedHashMap<>();
        for (String key : keys) {
            Class<? extends ICanalDataSyncHandler> handlerCls = CanalDataHandlerFactory.getInstance().getServiceClass(key);

            try {
                Field field = handlerCls.getField("PROPERTIES_DESP");
                if (field != null) {
                    String desp = field.get(handlerCls) + "";
                    resultMap.put(key, desp);
                } else {
                    resultMap.put(key, "");
                }
            } catch (NoSuchFieldException e) {
                log.warn(handlerCls + "不存在附件参数描述（PROPERTIES_DESP）属性");
            } catch (SecurityException e) {
                log.error(handlerCls + "获取附件参数描述（PROPERTIES_DESP）属性错误：", e);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                log.error(handlerCls + "获取附件参数描述（PROPERTIES_DESP）的值错误：", e);
            }
        }
        return resultMap;

    }

}
